package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author gakki
 * @create 2022/5/2 15:25
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    /**
     * 判断是否关联category
     * @param id
     */
    @Override
    public void deleteCategory(Long id) {
        //是否关联dish
        LambdaQueryWrapper<Dish> lambdaQueryWrapperDish = new LambdaQueryWrapper<>();
        lambdaQueryWrapperDish.eq(Dish::getCategoryId, id);
        int countDish = dishService.count(lambdaQueryWrapperDish);
        if (countDish > 0) {
            throw new CustomException("该category已关联菜品，无法删除！");
        }

        //是否关联setmeal
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapperSetmeal = new LambdaQueryWrapper<>();
        lambdaQueryWrapperSetmeal.eq(Setmeal::getCategoryId, id);
        int countSetmeal = setmealService.count(lambdaQueryWrapperSetmeal);
        if (countDish > 0) {
            throw new CustomException("该category已关联套餐，无法删除！");
        }

        //正常删除
        super.removeById(id);
    }
}
